package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.*;
import cn.wolfcode.luowowo.query.StrategyQuery;
import cn.wolfcode.luowowo.redis.StrategyStatisVO;
import cn.wolfcode.luowowo.repository.StrategyCatalogRepository;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
//@Transactional  暂时先别管事务
public class StrategyServiceImpl implements IStrategyService {
    
    @Autowired
    private StrategyRepository repository;
    
    @Autowired
    private MongoTemplate template;
    //分类对象
    @Autowired
    private StrategyCatalogRepository catalogRepositorye;
    //主题对象
    @Autowired
    private StrategyThemeServiceImpl strategyThemeService;
    //目的地对象
    @Autowired
    private DestinationServiceImpl destinationService;
    //查询单个方法
    public Strategy get(String id) {
        Optional<Strategy> optional = repository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }
    //条件查询
    //page对象里面包括: 总页数 每页显示条数......
    public Page<Strategy> query(StrategyQuery qo) {
        /*创建一个空的条件*/
        Query query = new Query();
        if (StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }
        /*模糊高查*/
        if (StringUtils.hasLength(qo.getKeyword())) {
            /*通过name模糊查询*/
            query.addCriteria(Criteria.where("name").regex(".*" + qo.getKeyword() + ".*"));
        }
        /*工具类传进条件后 进行数据的排序与分页*/
        return DBHelper.query(template, Strategy.class, query, qo.getPageable());
    }
    /*查询全部的内容*/
    public List<Strategy> list() {
        return repository.findAll();
    }
    /* *//*获取前端吐司*//*
    public List<Strategy> getToasts(String parentId) {
        *//*如果前端的区域id为空的话*//*
        if (!StringUtils.hasLength(parentId)) {
            //返回一个空集合
            return Collections.emptyList();
        }
        List<Strategy> list = new ArrayList<>();
        //查询当前目的地
        createToast(list, parentId);
        Collections.reverse(list);  //取反
        return list;
    }
    
    //创建toast 也可以用while的方法 这里使用递归的方式
    private void createToast(List<Strategy> list, String parentId) {
        *//*通过id获取对象*//*
        Strategy strategy = this.get(parentId);
        *//*对象存入list集合中*//*
        list.add(strategy);
        *//*判断id是否为空*//*
        if (StringUtils.hasLength(strategy.getParentId())) {
            *//*不为空说明是有父类的 就再调用递归方法再循环一次
     * 为空就会跳过这个方法 返回结果list*//*
            createToast(list, strategy.getParentId());
        }
    }
    */
    
    /*    *//**
     * 模糊查询
     * @param keyword 查询字段
     * @return
     *//*
    @Override
    public Strategy getByName(String keyword) {
        return repository.findByName(keyword);
    }*/
    
    /**
     * 删除方法
     *
     * @param id 删除的id
     */
    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }
    
    /**
     * 添加与保存的方法
     *
     * @param strategy
     */
    @Override
    public void saveOrUpdate(Strategy strategy) {
        //有些数据是前端不能设置的,需要后端进行查询添加
        //目的地name
        StrategyCatalog strategyCatalog = catalogRepositorye.findById(strategy.getCatalogId()).get();
        strategy.setDestName(strategyCatalog.getDestName());
        //destid
        strategy.setDestId(strategyCatalog.getDestId());
        //分类name
        strategy.setCatalogName(strategyCatalog.getName());
        //主题name
        StrategyTheme strategyTheme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(strategyTheme.getName());
        //判断是否为国内外
        List<Destination> toasts = destinationService.getToasts(strategy.getDestId());
        strategy.setIsabroad("中国".equals(toasts.get(0).getName()) ? Strategy.ABROAD_NO : Strategy.ABROAD_YES);
        
        //因为保存的时候是会加上时间戳的,所以要进行分辨是新增还是编辑
        if (StringUtils.hasLength(strategy.getId())) {
            //有长度是编辑 编辑的话是全量修改 所以有些数据是需要单独的修改
            Query query = new Query();
            /*用id作为条件进行更改*/
            query.addCriteria(Criteria.where("_id").is(strategy.getId()));
            DBHelper.update(template, query, strategy, "themeId", "catalogId", "title", "subTitle", "coverUrl", "state", "summary", "content",
                    "destName", "destId", "catalogName", "themeName", "isabroad");
            
        } else {
            //没长度是保存
            //时间戳
            strategy.setCreateTime(new Date());
            repository.save(strategy);
        }
    }
    
    @Override
    public void changeState(String id, int state) {
        
        //设置条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        //设置更改方法
        Update update = new Update();
        update.set("state", state);
        //调用更改方法 有单个修改和全部修改,这里用的全部修改
        template.updateMulti(query, update, Strategy.class);
    }
    
    /**
     * @param id
     * @return
     */
    @Override
    public List<Strategy> selectTitleByCataId(String id) {
        return repository.findByCatalogId(id);
    }
    
    /**
     * 点击率前三的三个攻略
     * @param destId
     * @return
     */
    @Override
    public List<Strategy> selectViewnumTop3(String destId) {
        //排序条件
        PageRequest pageRequest = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        //查询
        List<Strategy> byDestId = repository.findByDestId(destId,pageRequest);
        
        return byDestId;
    }
    //持久化攻略的统计数据
    @Override
    public void updateStatis(Strategy strategy) {
        //用最笨的方法save
        repository.save(strategy);
        System.out.println("序列化成功");
    }
    
    @Override
    public List<Strategy> findByDestName(String name) {
        return repository.findByDestName(name);
    }
}
